package com.example.demo.utility;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 定时器工具类
 * 定时器框架 启动,暂停,结束
 *
 * @author yzh
 * @date 2022/11/21
 */
public class Quartz {
    //使用默认的配置
    private static final SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    /**
     * @param jobName  任务名称
     * @param time     单位秒
     * @param jobClass 计时器任务实体类
     */
    public static void addJob(String jobName, int time, Class<? extends Job> jobClass) {
        //创建任务
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName).build();
        //创建触发器 每 5 秒钟执行一次
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(time).repeatForever())
                .build();
        try {
            //获取实例化的 Scheduler。
            Scheduler scheduler = getScheduler();
            //将任务及其触发器放入调度器
            scheduler.scheduleJob(jobDetail, trigger);
            //调度器开始调度任务
            if (!scheduler.isShutdown()) {
                scheduler.start();
                System.out.println(String.format("启动任务，jobName：%s", jobName));
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    //获取一个默认的Scheduler对象
    private static Scheduler getScheduler() {
        try {
            return schedulerFactory.getScheduler();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return null;
    }

    //停止任务--再启动需要从新初始化
    public static void stopScheduler() {
        Scheduler scheduler = getScheduler();
        try {
            /**
             *  shutdown(true)表示等待所有正在执行的任务执行完毕后关闭Scheduler
             *  shutdown(false),即shutdown()表示直接关闭Scheduler
             */
            scheduler.shutdown();
            System.out.println("------停止任务----");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    //暂停所有任务执行
    public static void standbyScheduler() {
        Scheduler scheduler = getScheduler();
        try {
            scheduler.standby();
            System.out.println("-----暂停任务----");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除任务
     *
     * @param jobName
     */
    public void deleteJob(String jobName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName);
            Scheduler scheduler = getScheduler();
            scheduler.pauseTrigger(triggerKey);   // 停止触发器
            scheduler.unscheduleJob(triggerKey);  // 移除触发器
            scheduler.deleteJob(JobKey.jobKey(jobName));
            System.out.println(String.format("删除任务，jobName：%s ,jobGroupName:%s", jobName));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

